import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import {
  FluentProvider,
  webLightTheme,
  makeStyles,
  Button,
  Avatar,
  Menu,
  MenuTrigger,
  MenuPopover,
  MenuList,
  MenuItem,
  Badge,
  Tooltip,
} from '@fluentui/react-components';
import {
  Navigation20Regular,
  Home20Regular,
  ContactCard20Regular,
  DocumentBulletList20Regular,
  ChartMultiple20Regular,
  Shield20Regular,
  DataUsage20Regular,
  Settings20Regular,
  SignOut20Regular,
  ChevronLeft20Regular,
  ChevronRight20Regular,
  Alert20Regular,
} from '@fluentui/react-icons';
import { RootState } from '../store/store';
import { logout } from '../store/slices/authSlice';
import Sidebar from './Sidebar';
import TopBar from './TopBar';

const useStyles = makeStyles({
  layout: {
    display: 'flex',
    height: '100vh',
    backgroundColor: '#F2F3F5',
  },
  sidebar: {
    width: '280px',
    backgroundColor: '#FFFFFF',
    borderRight: '1px solid #E5E6EB',
    transition: 'width 0.3s ease',
    zIndex: 1000,
  },
  sidebarCollapsed: {
    width: '64px',
  },
  mainContent: {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
    overflow: 'hidden',
  },
  topBar: {
    height: '64px',
    backgroundColor: '#FFFFFF',
    borderBottom: '1px solid #E5E6EB',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '0 24px',
    zIndex: 999,
  },
  content: {
    flex: 1,
    padding: '24px',
    overflow: 'auto',
    backgroundColor: '#F2F3F5',
  },
  leftSection: {
    display: 'flex',
    alignItems: 'center',
    gap: '16px',
  },
  rightSection: {
    display: 'flex',
    alignItems: 'center',
    gap: '16px',
  },
  pageTitle: {
    fontSize: '20px',
    fontWeight: '600',
    color: '#1D2129',
    margin: 0,
  },
  collapseButton: {
    minWidth: '32px',
    minHeight: '32px',
  },
  notificationButton: {
    minWidth: '40px',
    minHeight: '40px',
    borderRadius: '50%',
    position: 'relative',
  },
  userSection: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
  },
  userName: {
    fontSize: '14px',
    fontWeight: '500',
    color: '#1D2129',
  },
  userRole: {
    fontSize: '12px',
    color: '#86909C',
  },
  '@media (max-width: 768px)': {
    sidebar: {
      position: 'fixed',
      left: '-280px',
      zIndex: 1100,
    },
    sidebarVisible: {
      left: '0',
    },
    mainContent: {
      marginLeft: '0',
    },
  },
});

interface LayoutProps {
  children: React.ReactNode;
}

const Layout: React.FC<LayoutProps> = ({ children }) => {
  const classes = useStyles();
  const location = useLocation();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  
  const { user } = useSelector((state: RootState) => state.auth);

  const getPageTitle = () => {
    const pathMap: Record<string, string> = {
      '/dashboard': '仪表盘',
      '/opportunities': '商机管理',
      '/business-plans': '商务计划',
      '/progress-tracking': '进展跟踪',
      '/risk-management': '风险管理',
      '/analytics': '数据分析',
      '/settings': '系统设置',
    };
    
    return pathMap[location.pathname] || '企业商机跟踪管理系统';
  };

  const handleLogout = () => {
    dispatch(logout());
    navigate('/login');
  };

  const toggleSidebar = () => {
    setSidebarCollapsed(!sidebarCollapsed);
  };

  const toggleMobileMenu = () => {
    setMobileMenuOpen(!mobileMenuOpen);
  };

  return (
    <div className={classes.layout}>
      {/* 侧边栏 */}
      <div className={`${classes.sidebar} ${sidebarCollapsed ? classes.sidebarCollapsed : ''}`}>
        <Sidebar 
          collapsed={sidebarCollapsed} 
          onToggle={toggleSidebar}
          mobileOpen={mobileMenuOpen}
          onMobileToggle={toggleMobileMenu}
        />
      </div>

      {/* 主内容区 */}
      <div className={classes.mainContent}>
        {/* 顶部栏 */}
        <div className={classes.topBar}>
          <div className={classes.leftSection}>
            <Button
              appearance="subtle"
              icon={sidebarCollapsed ? <ChevronRight20Regular /> : <ChevronLeft20Regular />}
              onClick={toggleSidebar}
              className={classes.collapseButton}
            />
            <h1 className={classes.pageTitle}>{getPageTitle()}</h1>
          </div>

          <div className={classes.rightSection}>
            {/* 通知按钮 */}
            <Tooltip content="通知" relationship="label">
              <Button
                appearance="subtle"
                icon={<Alert20Regular />}
                className={classes.notificationButton}
              >
                <Badge 
                  appearance="filled" 
                  color="danger" 
                  size="small"
                  style={{ position: 'absolute', top: '4px', right: '4px' }}
                >
                  3
                </Badge>
              </Button>
            </Tooltip>

            {/* 用户菜单 */}
            <Menu>
              <MenuTrigger disableButtonEnhancement>
                <div className={classes.userSection} style={{ cursor: 'pointer' }}>
                  <Avatar
                    name={user?.username || '用户'}
                    image={{ src: user?.avatar }}
                    size={32}
                  />
                  <div>
                    <div className={classes.userName}>{user?.username || '用户'}</div>
                    <div className={classes.userRole}>{user?.role || '员工'}</div>
                  </div>
                </div>
              </MenuTrigger>
              <MenuPopover>
                <MenuList>
                  <MenuItem icon={<Settings20Regular />} onClick={() => navigate('/settings')}>
                    个人设置
                  </MenuItem>
                  <MenuItem icon={<SignOut20Regular />} onClick={handleLogout}>
                    退出登录
                  </MenuItem>
                </MenuList>
              </MenuPopover>
            </Menu>
          </div>
        </div>

        {/* 页面内容 */}
        <div className={classes.content}>
          {children}
        </div>
      </div>
    </div>
  );
};

export default Layout;
